<?php

/**
 *
 * @author Anthony Straetman
 *
 */
class LoginController extends PlonkController {

	/**
	 * The views allowed for this module
	 * @var array
	 */
	protected $views = array(
		'login'
	);

	/**
	 * The actions allowed for this module
	 * @var array
	 */
	protected $actions = array(
		'login'
	);

	/**
	 * The form errors
	 * @var array
	 */
	private $formErrors = array();

	public function doLogin() {
		$email = trim((string) PlonkFilter::getPostValue('email'));
		$password = trim((string) PlonkFilter::getPostValue('password'));

		try {
			LoginDB::login($email, $password);
			PlonkWebsite::redirect($_SERVER['PHP_SELF'] . '?' . PlonkWebsite::$moduleKey . '=home');
		} catch (UserNotFoundException $e) {
			$this->formErrors[] = $e->getMessage();
		} catch (IncorrectPasswordException $e) {
			$this->formErrors[] = $e->getMessage();
		} catch(Exception $e) {
			PlonkWebsite::redirect($_SERVER['PHP_SELF'] . '?' . PlonkWebsite::$moduleKey . '=oops');
		}
	}

	public function showLogin() {
		// ---------- Main template stuff ---------- //
		
		$this->setMainTemplate();
		
		// ---------- Page template stuff ---------- //
		$this->pageTpl->assign('formUrl', 'index.php?module=login');
		
		// ---------- Error stuff ---------- //
		$this->handleErrors();
	}
	
	private function handleErrors() {
		if (sizeof($this->formErrors) > 0) {
			$this->pageTpl->assignOption('oErrors');
			$this->pageTpl->setIteration('iErrors');
			foreach ($this->formErrors as $error) {
				$this->pageTpl->assignIteration('error', $error);
				$this->pageTpl->refillIteration();
			}
			$this->pageTpl->parseIteration();
		}
	}
	
	private function setNavigationOptions() {
		if(PlonkSession::exists('id')) { 
			// User logged in
			$this->mainTpl->assignOption('oLogout');
		} else { 
			// User logged out
			$this->mainTpl->assignOption('oLogin');
			$this->mainTpl->assignOption('oRegister');
		}
	}
	
	private function setMainTemplate() {
		$this->mainTpl->assign('pageTitle', 'Login');
		$this->mainTpl->assign('pageMeta', '<link rel="stylesheet" href="modules/login/css/login.css" />' . PHP_EOL . '<script type="text/javascript" src="modules/login/js/login.js"></script>');
		
		$this->setNavigationOptions();
	}

}

// EOF